<?php

namespace App\Admin\Actions\Grid\User;

use App\Admin\Utils\DownUtils;
use App\Models\User\WxUserInviteTempCode;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class UserInviteTmpCodeDownBatchAction extends BatchAction
{
    /**
     * @return string
     */
	protected $title = '批量下载';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $ids = $this->getKey();
        if(_empty_($ids)){
            return $this->response()->warning('没有勾选');
        }
        $codes = WxUserInviteTempCode::whereIn('id', $ids)
            ->get(['id', 'code'])
            ->map(function ($item) {
                return [
                    'name' => 'id-'.$item->id,
                    'url' => $item->code
                ];
            })->toArray();
        if($codes){
            $zip_file_path = DownUtils::down_invite_temp_code($codes);
            return $this->response()->download($zip_file_path);
        }else{
            return $this->response()->error('下载程序出错');
        }
    }

    /**
	 * @return string|array|void
	 */
	public function confirm()
	{
		 return ['确定下载选中的推广码?'];
	}

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [];
    }
}
